const { Order, User } = require('../models');
const logger = require('../utils/logger');

class OrderStatusService {
  /**
   * 订单状态流转规则
   */
  static STATUS_FLOW = {
    'pending': ['confirmed', 'cancelled'],
    'confirmed': ['processing', 'cancelled'],
    'processing': ['printing', 'cancelled'],
    'printing': ['completed', 'cancelled'],
    'completed': [], // 已完成订单不能再更改
    'cancelled': [] // 已取消订单不能再更改
  };

  /**
   * 状态显示文本映射
   */
  static STATUS_TEXT = {
    'pending': '待确认',
    'confirmed': '已确认',
    'processing': '处理中',
    'printing': '打印中',
    'completed': '已完成',
    'cancelled': '已取消'
  };

  /**
   * 状态优先级（用于排序）
   */
  static STATUS_PRIORITY = {
    'pending': 1,
    'confirmed': 2,
    'processing': 3,
    'printing': 4,
    'completed': 5,
    'cancelled': 0
  };

  /**
   * 验证状态流转是否合法
   * @param {string} currentStatus 当前状态
   * @param {string} newStatus 新状态
   * @returns {boolean} 是否合法
   */
  static isValidStatusTransition(currentStatus, newStatus) {
    if (!currentStatus || !newStatus) return false;
    
    const allowedStatuses = this.STATUS_FLOW[currentStatus];
    return allowedStatuses && allowedStatuses.includes(newStatus);
  }

  /**
   * 获取状态显示文本
   * @param {string} status 状态
   * @returns {string} 显示文本
   */
  static getStatusText(status) {
    return this.STATUS_TEXT[status] || '未知状态';
  }

  /**
   * 获取状态优先级
   * @param {string} status 状态
   * @returns {number} 优先级
   */
  static getStatusPriority(status) {
    return this.STATUS_PRIORITY[status] || 0;
  }

  /**
   * 获取可用的下一步状态
   * @param {string} currentStatus 当前状态
   * @returns {Array} 可用状态列表
   */
  static getAvailableNextStatuses(currentStatus) {
    const allowedStatuses = this.STATUS_FLOW[currentStatus] || [];
    return allowedStatuses.map(status => ({
      status,
      text: this.getStatusText(status),
      priority: this.getStatusPriority(status)
    }));
  }

  /**
   * 更新订单状态
   * @param {number} orderId 订单ID
   * @param {string} newStatus 新状态
   * @param {object} options 选项
   * @returns {Promise<object>} 更新结果
   */
  static async updateOrderStatus(orderId, newStatus, options = {}) {
    const transaction = await Order.sequelize.transaction();
    
    try {
      const {
        adminId,
        adminNotes = '',
        estimatedCompletionTime,
        notifyUser = true
      } = options;

      // 获取订单
      const order = await Order.findByPk(orderId, {
        include: [
          {
            model: User,
            as: 'User',
            attributes: ['id', 'nickname', 'phone', 'points']
          }
        ],
        transaction
      });

      if (!order) {
        throw new Error('订单不存在');
      }

      // 验证状态流转
      if (!this.isValidStatusTransition(order.status, newStatus)) {
        throw new Error(`订单状态不能从 ${this.getStatusText(order.status)} 更改为 ${this.getStatusText(newStatus)}`);
      }

      const oldStatus = order.status;
      const updates = {
        status: newStatus,
        updatedAt: new Date()
      };

      // 添加管理员备注
      if (adminNotes) {
        const existingNotes = order.adminNotes || '';
        const timestamp = new Date().toLocaleString('zh-CN');
        const newNote = `[${timestamp}] ${adminNotes}`;
        updates.adminNotes = existingNotes ? `${existingNotes}\n${newNote}` : newNote;
      }

      // 设置预计完成时间
      if (estimatedCompletionTime) {
        updates.estimatedCompletionTime = new Date(estimatedCompletionTime);
      }

      // 处理特殊状态的业务逻辑
      await this.handleStatusSpecificLogic(order, newStatus, updates, transaction);

      // 更新订单
      await order.update(updates, { transaction });

      // 记录状态变更日志
      await this.logStatusChange(orderId, oldStatus, newStatus, adminId, adminNotes, transaction);

      await transaction.commit();

      // 发送通知（异步）
      if (notifyUser) {
        this.sendStatusChangeNotification(order, oldStatus, newStatus).catch(error => {
          logger.error('发送状态变更通知失败:', error);
        });
      }

      logger.info(`订单状态更新成功: ${order.orderNumber}, ${oldStatus} -> ${newStatus}, 管理员: ${adminId}`);

      return {
        success: true,
        message: '订单状态更新成功',
        data: {
          orderId,
          orderNumber: order.orderNumber,
          oldStatus,
          newStatus,
          statusText: this.getStatusText(newStatus)
        }
      };
    } catch (error) {
      await transaction.rollback();
      logger.error('更新订单状态失败:', error);
      throw error;
    }
  }

  /**
   * 处理特定状态的业务逻辑
   * @param {object} order 订单对象
   * @param {string} newStatus 新状态
   * @param {object} updates 更新数据
   * @param {object} transaction 事务
   */
  static async handleStatusSpecificLogic(order, newStatus, updates, transaction) {
    switch (newStatus) {
      case 'confirmed':
        // 确认订单时的逻辑
        updates.paymentStatus = 'paid';
        break;

      case 'processing':
        // 开始处理时的逻辑
        if (!updates.estimatedCompletionTime) {
          // 默认预计30分钟完成
          const estimatedTime = new Date();
          estimatedTime.setMinutes(estimatedTime.getMinutes() + 30);
          updates.estimatedCompletionTime = estimatedTime;
        }
        break;

      case 'printing':
        // 开始打印时的逻辑
        if (!updates.estimatedCompletionTime) {
          // 默认预计15分钟完成
          const estimatedTime = new Date();
          estimatedTime.setMinutes(estimatedTime.getMinutes() + 15);
          updates.estimatedCompletionTime = estimatedTime;
        }
        break;

      case 'completed':
        // 完成订单时的逻辑
        updates.actualCompletionTime = new Date();
        updates.paymentStatus = 'paid';

        // 给用户增加积分
        if (order.pointsEarned > 0 && order.User) {
          await order.User.update({
            points: order.User.points + order.pointsEarned
          }, { transaction });

          logger.info(`用户获得积分: ${order.User.id}, +${order.pointsEarned}分`);
        }
        break;

      case 'cancelled':
        // 取消订单时的逻辑
        await this.handleOrderCancellation(order, transaction);
        break;

      default:
        break;
    }
  }

  /**
   * 处理订单取消逻辑
   * @param {object} order 订单对象
   * @param {object} transaction 事务
   */
  static async handleOrderCancellation(order, transaction) {
    // 退还使用的积分
    if (order.pointsUsed > 0 && order.User) {
      await order.User.update({
        points: order.User.points + order.pointsUsed
      }, { transaction });

      logger.info(`退还积分: ${order.User.id}, +${order.pointsUsed}分`);
    }

    // 退还库存（如果有商品库存管理）
    if (order.items && Array.isArray(order.items)) {
      const { Product } = require('../models');
      
      for (const item of order.items) {
        if (item.productId) {
          const product = await Product.findByPk(item.productId, { transaction });
          if (product && product.stock !== null) {
            await product.update({
              stock: product.stock + item.quantity
            }, { transaction });

            logger.info(`退还库存: 商品${item.productId}, +${item.quantity}`);
          }
        }
      }
    }
  }

  /**
   * 记录状态变更日志
   * @param {number} orderId 订单ID
   * @param {string} oldStatus 旧状态
   * @param {string} newStatus 新状态
   * @param {number} adminId 管理员ID
   * @param {string} notes 备注
   * @param {object} transaction 事务
   */
  static async logStatusChange(orderId, oldStatus, newStatus, adminId, notes, transaction) {
    try {
      // 这里可以创建一个专门的状态变更日志表
      // 暂时使用简单的日志记录
      const logData = {
        orderId,
        oldStatus,
        newStatus,
        adminId,
        notes,
        timestamp: new Date()
      };

      logger.info('订单状态变更:', logData);

      // 如果有状态变更日志表，可以在这里插入记录
      // await OrderStatusLog.create(logData, { transaction });
    } catch (error) {
      logger.error('记录状态变更日志失败:', error);
      // 不抛出错误，避免影响主流程
    }
  }

  /**
   * 发送状态变更通知
   * @param {object} order 订单对象
   * @param {string} oldStatus 旧状态
   * @param {string} newStatus 新状态
   */
  static async sendStatusChangeNotification(order, oldStatus, newStatus) {
    try {
      // 这里可以集成消息通知服务
      // 例如：微信模板消息、短信通知等
      
      const notificationData = {
        userId: order.userId,
        orderNumber: order.orderNumber,
        oldStatusText: this.getStatusText(oldStatus),
        newStatusText: this.getStatusText(newStatus),
        timestamp: new Date()
      };

      logger.info('发送状态变更通知:', notificationData);

      // 实际的通知发送逻辑
      // await notificationService.sendOrderStatusNotification(notificationData);
    } catch (error) {
      logger.error('发送状态变更通知失败:', error);
    }
  }

  /**
   * 批量更新订单状态
   * @param {Array} orderIds 订单ID列表
   * @param {string} newStatus 新状态
   * @param {object} options 选项
   * @returns {Promise<object>} 批量更新结果
   */
  static async batchUpdateOrderStatus(orderIds, newStatus, options = {}) {
    const results = {
      success: [],
      failed: []
    };

    for (const orderId of orderIds) {
      try {
        const result = await this.updateOrderStatus(orderId, newStatus, options);
        results.success.push({
          orderId,
          result
        });
      } catch (error) {
        results.failed.push({
          orderId,
          error: error.message
        });
      }
    }

    return {
      success: results.success.length > 0,
      message: `成功更新 ${results.success.length} 个订单，失败 ${results.failed.length} 个`,
      data: results
    };
  }

  /**
   * 获取订单状态统计
   * @param {object} filters 过滤条件
   * @returns {Promise<object>} 统计结果
   */
  static async getOrderStatusStatistics(filters = {}) {
    try {
      const where = {};
      
      // 添加时间过滤
      if (filters.startDate || filters.endDate) {
        where.createdAt = {};
        if (filters.startDate) {
          where.createdAt[Op.gte] = new Date(filters.startDate);
        }
        if (filters.endDate) {
          where.createdAt[Op.lte] = new Date(filters.endDate);
        }
      }

      // 添加用户过滤
      if (filters.userId) {
        where.userId = filters.userId;
      }

      const { Op } = require('sequelize');
      
      const statistics = {};
      
      // 统计各状态的订单数量
      for (const status of Object.keys(this.STATUS_TEXT)) {
        const count = await Order.count({
          where: { ...where, status }
        });
        statistics[status] = {
          count,
          text: this.getStatusText(status),
          priority: this.getStatusPriority(status)
        };
      }

      // 总订单数
      statistics.total = await Order.count({ where });

      return {
        success: true,
        data: statistics
      };
    } catch (error) {
      logger.error('获取订单状态统计失败:', error);
      throw error;
    }
  }

  /**
   * 自动处理超时订单
   * @returns {Promise<object>} 处理结果
   */
  static async handleTimeoutOrders() {
    try {
      const { Op } = require('sequelize');
      const now = new Date();
      
      // 查找超时的待确认订单（超过30分钟自动取消）
      const timeoutPendingOrders = await Order.findAll({
        where: {
          status: 'pending',
          createdAt: {
            [Op.lt]: new Date(now.getTime() - 30 * 60 * 1000) // 30分钟前
          }
        }
      });

      const results = {
        cancelled: 0,
        failed: 0
      };

      for (const order of timeoutPendingOrders) {
        try {
          await this.updateOrderStatus(order.id, 'cancelled', {
            adminNotes: '系统自动取消：超时未确认',
            notifyUser: true
          });
          results.cancelled++;
        } catch (error) {
          logger.error(`自动取消订单失败: ${order.orderNumber}`, error);
          results.failed++;
        }
      }

      logger.info(`自动处理超时订单完成: 取消${results.cancelled}个，失败${results.failed}个`);

      return {
        success: true,
        message: `处理完成: 取消${results.cancelled}个订单`,
        data: results
      };
    } catch (error) {
      logger.error('自动处理超时订单失败:', error);
      throw error;
    }
  }
}

module.exports = OrderStatusService;